package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.contants.wemedia.WemediaContans;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.media.vo.WmNewsVo;
import com.usian.user.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmNewsService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@SuppressWarnings("All")
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 分页带条件查询自媒体文章列表
     * 每个用户对应自己的自媒体文章列表
     *
     * @param wmNewsPageReqDto 里面有
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //检查参数
        if (wmNewsPageReqDto == null) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "参数为空");
        }
        //分页初始化检查
        wmNewsPageReqDto.checkParam();
        //根据条件进行判断   模糊查询
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNews::getUserId, uid);//只查询当前用户下的文章信息
        //查看状态  当前面状态不为空时，进行查询
        lambdaQueryWrapper.eq(wmNewsPageReqDto.getStatus() != null, WmNews::getStatus, wmNewsPageReqDto.getStatus());
        //搜索关键字
        lambdaQueryWrapper.like(null != wmNewsPageReqDto.getKeyword(), WmNews::getTitle, wmNewsPageReqDto.getKeyword());
        //频道id
        lambdaQueryWrapper.eq(wmNewsPageReqDto.getChannelId() != null, WmNews::getChannelId, wmNewsPageReqDto.getChannelId());
        //时间查询  1、大于等于  小于等于的方式（可以单条件，也可以两个条件一起）  2、区间查询between  and（这里面的值不能为空）   根据前端需求来使用
        //mybatisplus中大于等于（ge）   小于等于（le）
//        lambdaQueryWrapper.ge(wmNewsPageReqDto.getBeginPubDate()!=null,WmNews::getPublishTime,wmNewsPageReqDto.getBeginPubDate());
//        lambdaQueryWrapper.le(wmNewsPageReqDto.getEndPubDate()!=null,WmNews::getPublishTime,wmNewsPageReqDto.getEndPubDate());
//区间查询
        lambdaQueryWrapper.between(wmNewsPageReqDto.getEndPubDate() != null && wmNewsPageReqDto.getBeginPubDate() != null, WmNews::getPublishTime, wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getEndPubDate());
//分页
        IPage<WmNews> iPage = this.page(new Page<>(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize()), lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize(), (int) iPage.getTotal());
        responseResult.setData(iPage.getRecords());
        return responseResult;

    }

    /**
     * 自媒体文章发布
     * @param dto
     * @param isSubmit 是否为提交 1 为提交   0为草稿
     * @return
     */
    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1、检查参数
        if (dto == null) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "参数为空");
        }
        WmNews wmNews = new WmNews();//创建对象，为了保存和修改文章信息
        //将打dto中的文章信息复给文章对象  源：dto  复制给wmNews
        BeanUtils.copyProperties(dto, wmNews);//spring提供的，复制属性
        //判断type是否为-1  如果为-1 先设置为空，一会需要在进行赋值传到数据库
        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //转换前端传递到后端的图片  前端是数组类型 但是  数据库使用的是字符串类型中间使用，拼接
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String images = "";
            for (String image : dto.getImages()) {
                images += image + ",";
            }
            wmNews.setImages(images.substring(0, images.length() - 1));
        }
        //2、保存或修改文章(wm_news)
        saveWmNews(wmNews, isSubmit);
        //3、关联文章与素材的关系
        String content = dto.getContent();
        //List<Map>  转为map泛型的集合
        List<Map> list = JSON.parseArray(content, Map.class);
        //素材集合
        List<String> materials = pickUpImageUrl(list);

        //3.1  关联内容中的图片与素材的关系（wm_news_material)
        //必须是发布状态才能保存
        if (WmNews.Status.SUBMIT.getCode() == isSubmit && materials.size() != 0) {

            saveRelativeInfoForNR(materials, wmNews.getId());
        }

        //3.2、关联封面中的图片与素材的关系,设置wm_news的type,自动
        if (WmNews.Status.SUBMIT.getCode() == isSubmit) {
            saveRelativeInfoForFM(materials, dto, wmNews);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.参数检查
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //2.查询数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.结果返回
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        return responseResult;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaContans.WM_NEWS_ENABLE_UP)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }

        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }

        //4.修改文章状态，同步到app端（后期做）TODO
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
            //修改文章中的状态
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, dto.getEnable()));
            Map map=new HashMap();
            map.put("article_id", wmNews.getArticleId());
            map.put("enable",dto.getEnable());
            rabbitTemplate.convertAndSend("DownOrUpExchange","DownOrUp",map);
        }
        //同步到App端
        //两种方式：  同步 通过Feign 调用article提供文章配置接口  进行修改
                    //异步 通过RabbitMQ 方式发送通知  上下架Id 然后文章配置信息监听  获取到对应进行操作
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public PageResponseResult findListAndPage(NewsAuthDto dto) {
        //1、检查参数
        if (dto==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"有问题");
        }
        //2、初始化分页
        dto.checkParam();
        //计算分页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if (dto.getTitle()!=null && !"".equals(dto.getTitle())){
            //会导致索引失效
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        List<WmNewsVo> list=wmNewsMapper.findListAndPage(dto);
        Integer total=wmNewsMapper.findListCount(dto);
        PageResponseResult pageResponseResult=new PageResponseResult();
        pageResponseResult.setData(list);
        pageResponseResult.setCurrentPage(dto.getPage());
        pageResponseResult.setSize(dto.getSize());
        pageResponseResult.setTotal(total);
        return pageResponseResult;
    }
@Autowired
private WmUserMapper wmUserMapper;
    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        //查询文章信息
        WmNews wmNews=getById(id);
        //查询作者
        WmUser wmUser=null;
        if (wmNews!=null && wmNews.getUserId() !=null){
            wmUser=wmUserMapper.selectById(wmNews.getUserId());
        }
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        return wmNewsVo;
    }


    /**
     * 保存素材与文章信息
     * @param materials
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        //1、获取数据库中素材信息
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmMaterial::getUrl, materials);
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId());
        List<WmMaterial> list = wmMaterialMapper.selectList(lambdaQueryWrapper);
        //2、通过图片的路径获取素材的id
        Map<String, Integer> map = list.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        List<String> materialIds = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (String url : materials) {
                String materialId = String.valueOf(map.get(url));
                //没找到
                if ("null".equals(materialId)) {
                    CatchCustomException.catchs(UserStatusCode.PARAM_FAIL, "图片有问题");
                }
                materialIds.add(materialId);
            }
        }
        //3、批量保存数据
        wmNewsMaterialMapper.saveRelationsByContent(materialIds, newsId, type);

    }

    /**
     * 保存封面与文章关系（封面）
     *
     * @param materials 内容素材  装的都是图片
     * @param dto
     */
    private void saveRelativeInfoForFM(List<String> materials, WmNewsDto dto, WmNews wmNews) {
        List<String> images = dto.getImages();
//   判断前端传递的类型  自动类型
        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //自动获取封面
            if (materials != null && materials.size() > 0 && materials.size() <= 2) {
                //单图
                wmNews.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());

            } else if (materials != null && materials.size() > 2) {
                wmNews.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
                //三图
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
            }
        }
        //转换前端传递到后端的图片  前端是数组类型 但是  数据库使用的是字符串类型中间使用，拼接
        if (images != null && images.size() > 0) {
            String image = "";
            for (String item : dto.getImages()) {
                image += item + ",";
            }
            wmNews.setImages(image.substring(0, image.length() - 1));
//修改wmNews  状态  因为开始的时候 保存了数据库了  在这个地方进行修改状态
            this.updateById(wmNews);
            //主图引用  保存关系
            if (images != null && images.size() > 0) {
                saveRelativeInfo(images, wmNews.getId(), WemediaContans.WM_COVER_REFERENCE);
            }
        }
    }

    /**
     * 保存素材与文章关系（内容）
     *
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForNR(List<String> materials, Integer newsId) {
        //内容引用
        saveRelativeInfo(materials, newsId, WemediaContans.WM_CONTENT_REFERENCE);
    }

    /**
     * 提取内容中的素材路径
     *
     * @param list
     * @return
     */
    private List<String> pickUpImageUrl(List<Map> list) {
        List<String> materials = new ArrayList<>();//素材集合
        //循环
        for (Map map : list) {
            if (map.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)) {
                materials.add((String) map.get("value"));
            }
        }
        return materials;
    }

    /**
     * 保存或修改文章
     *
     * @param wmNews
     * @param isStubmit
     */
    private void saveWmNews(WmNews wmNews, Short isStubmit) {
        wmNews.setStatus(isStubmit);//发布或者是草稿
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());//用户id
        wmNews.setCreatedTime(new Date());//创建时间时间
        wmNews.setSubmitedTime(new Date());//提交时间
        wmNews.setEnable((short) 1);//默认下架  因为还没进行审核
        //判断
        boolean flag = false;
        if (wmNews.getId() == null) {
            //保存  执行添加操作
            flag = save(wmNews);
        } else {
            //修改
            //   修改之前删除素材和文章的关系(只需要找到id就可以删除)
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            //根据文章id删除关系表数据
            lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(lambdaQueryWrapper);
            flag = updateById(wmNews);//修改对象

        }
        if (flag) {
            rabbitTemplate.convertAndSend("adminExchange", "admin", wmNews.getId());
        }
    }

    /**
     * 查询需要发布的文章id列表
     * @return
     */
    @Override
    public List<Integer> findRelease(){
        //获取状态为8（审核成功，待发布）的文章信息
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8).lt(WmNews::getPublishTime,new Date()));
        List<Integer> resultList = list.stream().map(WmNews::getId).collect(Collectors.toList());//流式编程转为list集合
        return resultList;
    }
}